/// <reference path="../../index.d.ts" />
const Service = require("egg").Service
class Msg extends Service {
	constructor(ctx) {
		super(ctx)
		this.serverConfig = this.config.serverConfig
		this.ApplicationUser = this.app.model.ApplicationUser
		this.UserKfMsg = this.app.model.UserKfMsg
	}
	/**
	 * 处理文本消息
	 */
	async handText() {
		let ctx = this.ctx
		let userText = ctx.wechatObj.Content
		let keyword = (await this.app.cache.keyWord).find(o => {
			return o.aid == ctx.wechat.aid && userText.includes(o.trigger_key) && o.trigger_type == 1
		})

		let userMsg = {
			oid: ctx.wechatUser.id, to_user: 0,
			msg: JSON.stringify({
				textContent: userText
			}),
			respone_stat: 0
		}

		if (ctx.wechat.app_type <= 2) {
			//  ctx
			if (keyword) {
				let content = JSON.parse(keyword.respone_set)

				let sendRes = await ctx.service.wechatUser.sendMsg(ctx.wechatObj.FromUserName, content, keyword.response_type, ctx.wechatUser.id)
				if (sendRes)
					userMsg.respone_stat = 1
			}  // 发送消息记录
			await this.UserKfMsg.create(userMsg)
			return
		}
		let resMsg
		if (!keyword) {
			ctx.xmlBody.Content = "服务器不理解"
		} else {
			let content = JSON.parse(keyword.respone_set)
			userMsg.respone_stat = 1
			resMsg = {
				oid: 0,
				to_user: ctx.wechatUser.id,
				msg: keyword.respone_set,
				respone_stat: 1
			}
			if (keyword.response_type == 1) {
				ctx.xmlBody.Content = content.textContent
			} else if (keyword.response_type == 2) {
				ctx.xmlBody.MsgType = "news"
				ctx.xmlBody.Articles = [
					{
						Description: content.imgDesc,
						PicUrl: this.serverConfig.imgServer + content.imgPath,
						Title: content.imgTitle,
						Url: content.imgHref
					}
				]
				ctx.xmlBody.ArticleCount = 1
			}
		}

		let msgList = [userMsg]
		if (resMsg) {
			msgList.push(resMsg)
		}
		await this.UserKfMsg.bulkCreate(msgList)
		return
	}

	async handEvent() {
		let ctx = this.ctx
		if (ctx.wechatObj.Event == "user_enter_tempsession") {
			this.handPromEnterKf()
		}
	}

	/**
	 * 小程序
	 */
	async handPromEnterKf() {
		// 自动回复的消息
		// user_enter_tempsession
		let ctx = this.ctx

		let keyword = (await this.app.cache.keyWord).find(o => {
			return o.aid == ctx.wechat.aid && o.trigger_type == 2
		})
		if (keyword) {
			let content = JSON.parse(keyword.respone_set)
			await ctx.service.wechatUser.sendMsg(ctx.wechatObj.FromUserName, content, keyword.response_type, ctx.wechatUser.id)
		}
		/* else {// 默认发送
			await ctx.service.wechatUser.sendMsg(ctx.wechatObj.FromUserName, {textContent: ":你好"}, 1, ctx.wechatUser.id)
		} */
	}
}
module.exports = Msg